import os
import asyncio
import json
from pathlib import Path
from urllib.parse import urlencode
from playwright.async_api import async_playwright


def read_env_value(key):
    v = os.getenv(key)
    if v:
        return v
    env_path = Path(__file__).resolve().parents[1] / 'luogu-snap' / '.env'
    if not env_path.exists():
        return ''
    for line in env_path.read_text(encoding='utf-8').splitlines():
        if line.strip().startswith(key + '='):
            return line.split('=', 1)[1].strip()
    return ''


async def main():
    user_id = read_env_value('LUOGU_USER_ID') or '322081'
    cookie = read_env_value('LUOGU_COOKIE')
    out_dir_raw = read_env_value('OUTPUT_DIR')
    out_dir = Path(out_dir_raw or (Path.cwd() / 'artifacts' / f'luogu-{user_id}' / 'inspect'))
    out_dir.mkdir(parents=True, exist_ok=True)
    list_url = f'https://www.luogu.com.cn/record/list?user={user_id}&page=104'
    async with async_playwright() as pw:
        browser = await pw.chromium.launch(headless=False)
        storage = Path(__file__).resolve().parents[1] / 'artifacts' / f'luogu-{user_id}' / 'storage_state.json'
        if storage.exists():
            context = await browser.new_context(storage_state=str(storage))
        else:
            context = await browser.new_context()
        page = await context.new_page()
        headers = {'User-Agent': 'Mozilla/5.0'}
        if cookie:
            headers['Cookie'] = cookie
        await page.set_extra_http_headers(headers)
        await page.goto(list_url)
        await page.wait_for_timeout(1000)
        list_html_path = out_dir / 'list_page_104.html'
        list_png_path = out_dir / 'list_page_104.png'
        await (await page.query_selector('body')).screenshot(path=str(list_png_path))
        list_html = await page.content()
        list_html_path.write_text(list_html, encoding='utf-8')
        links = await page.evaluate("""
        (() => {
          const as = Array.from(document.querySelectorAll('a'));
          return Array.from(new Set(as.map(a => a.href).filter(h => h.includes('/record/') && !h.includes('/record/list'))));
        })()
        """)
        detail_info = {}
        first_link = links[0] if links else ''
        if first_link:
            await page.goto(first_link)
            await page.wait_for_timeout(1000)
            rid = await page.evaluate(r"""
            (() => {
              const m = location.pathname.match(/record\/(\d+)/);
              return m ? m[1] : '';
            })()
            """)
            detail_html_path = out_dir / f'detail_page_{rid or "first"}.html'
            detail_png_path = out_dir / f'detail_page_{rid or "first"}.png'
            await (await page.query_selector('body')).screenshot(path=str(detail_png_path))
            detail_html = await page.content()
            detail_html_path.write_text(detail_html, encoding='utf-8')
            try:
                tab = page.locator('text=源代码').first
                await tab.click()
                await page.wait_for_timeout(500)
            except Exception:
                pass
            code_text = await page.evaluate(r"""
            (() => {
              const el = document.querySelector('pre code') || document.querySelector('pre') || document.querySelector('code');
              return el ? el.textContent : '';
            })()
            """)
            detail_info = {
                'rid': rid,
                'code_length': len(code_text or ''),
                'detail_html': str(detail_html_path),
                'detail_png': str(detail_png_path)
            }
        inspect_json = {
            'list_url': list_url,
            'list_html': str(list_html_path),
            'list_png': str(list_png_path),
            'record_links_count': len(links),
            'first_record_link': first_link,
            'detail_info': detail_info
        }
        (out_dir / 'inspect.json').write_text(json.dumps(inspect_json, ensure_ascii=False, indent=2), encoding='utf-8')
        await browser.close()
        print('Inspect outputs at', out_dir)


if __name__ == '__main__':
    asyncio.run(main())
